import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;

@WebServlet("/AlipayServlet")
public class AlipayServlet extends HttpServlet {
    // 支付宝网关
    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    // 应用ID
    private static final String APP_ID = "你的APPID";
    // 商户私钥
    private static final String MERCHANT_PRIVATE_KEY = "你的商户私钥";
    // 支付宝公钥
    private static final String ALIPAY_PUBLIC_KEY = "你的支付宝公钥";
    // 编码格式
    private static final String CHARSET = "UTF-8";
    // 返回格式
    private static final String FORMAT = "json";
    // 签名方式
    private static final String SIGN_TYPE = "RSA2";
    // 支付成功后的回调页面
    private static final String RETURN_URL = "http://你的域名/payment_success.html";
    // 支付宝服务器异步通知页面
    private static final String NOTIFY_URL = "http://你的域名/alipay_notify";
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        BufferedReader reader = request.getReader();
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        String jsonStr = stringBuilder.toString();
        // 添加调试日志
        System.out.println("接收到的JSON数据: " + jsonStr);

        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            
            // 获取所有传递的参数
            String chapterId = jsonObj.getString("chapter_id");
            String chapterTitle = jsonObj.getString("chapter_title");
            String novelName = jsonObj.getString("novel_name");
            String price = jsonObj.getString("price");
            String subject = jsonObj.getString("subject");
            String body = jsonObj.getString("body");
            
            // 创建AlipayClient实例
            AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL, APP_ID, MERCHANT_PRIVATE_KEY, FORMAT, 
                CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE
            );

            // 创建API对应的request
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(RETURN_URL);
            alipayRequest.setNotifyUrl(NOTIFY_URL);

            // 构建订单参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", generateOrderNo(chapterId)); // 生成订单号
            bizContent.put("total_amount", price);
            bizContent.put("subject", subject);
            bizContent.put("body", body);
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

            alipayRequest.setBizContent(bizContent.toString());

            // 调用SDK生成表单
            AlipayTradePagePayResponse alipayResponse = alipayClient.pageExecute(alipayRequest);
            if(alipayResponse.isSuccess()){
                response.setContentType("text/html;charset=" + CHARSET);
                response.getWriter().write(alipayResponse.getBody());
                response.getWriter().flush();
            } else {
                response.setStatus(500);
                response.getWriter().write("生成支付订单失败");
            }
            
        } catch (Exception e) {
            System.err.println("支付宝接口调用错误: " + e.getMessage());
            response.setStatus(500);
            response.getWriter().write("支付接口调用失败");
            return;
        }
    }

    // 生成订单号
    private String generateOrderNo(String chapterId) {
        return "CH" + chapterId + System.currentTimeMillis();
    }
} 